今天來綁定viewpager與tablayout
首先要建立一個viewpager的adapter
class MainPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
var fragmentList: MutableList<Fragment> = ArrayList()
var fragmentTitle: MutableList<String> = ArrayList()
override fun getItem(position: Int): Fragment {
return fragmentList[position]
}
override fun getCount(): Int {
return fragmentList.size
}
fun addFragment(fragment: Fragment, title: String) {
fragmentList.add(fragment)
fragmentTitle.add(title)
}
override fun getPageTitle(position: Int): CharSequence? {
return fragmentTitle[position]
}
}
接著在activity
class FragmentActivity : BaseActiivity(){
private val fragmentViewModel by lazy {
initViewModel(application , FragmentViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = DataBindingUtil.setContentView<ActivityFragmentBinding>(this,R.layout.activity_fragment)
binding.lifecycleOwner = this
binding.viewmodel = fragmentViewModel
val mainpagerAdapter = MainPagerAdapter(supportFragmentManager)
mainpagerAdapter.addFragment(OneFragment(),"one")
mainpagerAdapter.addFragment(TwoFragment(),"two")
mainpagerAdapter.addFragment(ThreeFragment(),"three")
binding.viewPager.adapter = mainpagerAdapter
binding.viewPager.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(binding.TabLayout))
binding.TabLayout.addOnTabSelectedListener(object : OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
when (tab.position) {
0 -> binding.viewPager.currentItem = 0
1 -> binding.viewPager.currentItem = 1
3 -> binding.viewPager.currentItem = 2
}
}
override fun onTabUnselected(tab: TabLayout.Tab) {}
override fun onTabReselected(tab: TabLayout.Tab) {}
})
}
}